package com.tghhh.gkrpc;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 表示一个服务描述，一个具体方法的签名(所在的类，方法名称，返回类型，参数列表)
 *
 * @author Zhikang.Peng
 * @version 1.0
 * @email thghh@qq.com
 * @date 2020/4/10 16:53
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ServiceDescriptor {
    private String clazz;
    private String method;
    private String returnType;
    private String[] parameterTypes;

    /**
     *  从对象实例和方法对象中构成成一个服务描述对象
     * @param clazz
     * @param method
     * @return
     */
    public static ServiceDescriptor from(Class clazz, Method method) {
        ServiceDescriptor self = new ServiceDescriptor();
        self.setClazz(clazz.getName());
        self.setMethod(method.getName());
        self.setReturnType(method.getReturnType().getName());
        Class[] paramClasses = method.getParameterTypes();
        String[] paramType = new String[paramClasses.length];
        for (int i = 0; i < paramClasses.length; i++) {
            paramType[i] = paramClasses[i].getName();
        }
        self.setParameterTypes(paramType);
        return self;
    }

    @Override
    public int hashCode() {
        return toString().hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || this.getClass() != obj.getClass()) {
            return false;
        }
        return this.toString().equals(obj.toString());
    }

    @Override
    public String toString() {
        return "Class:" + clazz +
                ",Method:" + method +
                ",return:" + returnType +
                ",ParameterTypes:" + Arrays.toString(parameterTypes);
    }

}
